package cn.itcast.controller.log;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;


/**
 * 通知类 ,用来记录操作日志
 */
@Component
@Aspect
public class LogAspect {

    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;


    @Around("execution(* cn.itcast.controller.*.*.*(..)) && !execution(* cn.itcast.controller.system.SysLogController.*(..)) ")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {
        //得到一个syslog对象
        SysLog sysLog = new SysLog();

        //time,id赋值
        sysLog.setTime(new Date());
        sysLog.setId(UUID.randomUUID().toString());

        //ip赋值
        String ip = request.getRemoteAddr();
        sysLog.setIp(ip);

        //userName,CompanyId,CompanyName赋值
        User user = (User) session.getAttribute("loginUser");

        if (user!=null){
            sysLog.setUserName(user.getUserName());
            sysLog.setCompanyId(user.getCompanyId());
            sysLog.setCompanyName(user.getCompanyName());
        }

        //method赋值
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        sysLog.setMethod(methodName);

        //action赋值
        if (method.isAnnotationPresent(RequestMapping.class)){
            RequestMapping annotation = method.getAnnotation(RequestMapping.class);
            String action = annotation.name();
            sysLog.setAction(action);
        }

        sysLogService.save(sysLog);

        return pjp.proceed();
    }


}
